package cm.example.shoppingplatformspringboot.controller;

import cm.example.shoppingplatformspringboot.service.MinioService;
import cm.example.shoppingplatformspringboot.utils.ResponseUtil;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

import static cm.example.shoppingplatformspringboot.utils.ResponseUtil.generateResponse;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    @Resource
    private MinioService minioService;

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String url = minioService.uploadFile(file);
            return generateResponse("success", "文件上传成功", url);
        } catch (Exception e) {
            return generateResponse("error", "文件上传失败", e.getMessage());
        }
    }

    // 新增替换图片接口
    @PostMapping("/upload-with-replace")
    public ResponseEntity<Map<String, Object>> uploadFileWithReplace(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "oldImageUrl", required = false) String oldImageUrl) {

        try {
            // 上传新文件
            String newUrl = minioService.uploadFile(file);

            // 删除旧文件
            if (oldImageUrl != null && !oldImageUrl.isEmpty()) {
                minioService.safeDeleteFile(oldImageUrl);
            }

            return ResponseUtil.generateResponse("success", "文件替换成功", newUrl);
        } catch (Exception e) {
            return ResponseUtil.generateResponse("error", "文件操作失败: " + e.getMessage(), null);
        }
    }
}